package com.example.demo.service.impl;



import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.example.demo.constant.BaseException;
import com.example.demo.mapper.DataTablesMapper;
import com.example.demo.pojo.DataTables;
import com.example.demo.pojo.TableConstraint;
import com.example.demo.pojo.TableInfo;
import com.example.demo.service.DataTablesService;
import com.example.demo.vo.DataSourceVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DataTablesServiceImpl implements DataTablesService {

    @Autowired
    private DataTablesMapper dataTablesMapper;

    @Autowired
    private DruidDataSource druidDataSource;

    @Override
    public List<DataTables> findColumnDataByTableName(String dbName, String tableName) {
        return dataTablesMapper.findColumnDataByTableName(dbName, tableName);
    }

    @Override
    public List<TableConstraint> findConstraint(String dbName, String tableName) {
        return dataTablesMapper.findConstraint(dbName, tableName);
    }

    @Override
    public List<String> findTableNameByDbName(String dbName) {
        return dataTablesMapper.findTableNameByDbName(dbName);
    }

    @Override
    public List<TableInfo> findTableInfoByTableName(String dbName, String tableName) {
        return dataTablesMapper.findTableInfoByTableName(dbName, tableName);
    }

    @Override
    public void changeDataSource(DataSourceVO vo)  {
        try {
            DruidDataSource druidDataSource1 = new DruidDataSource();
            druidDataSource1.setUrl(vo.getUrl());
            druidDataSource1.setPassword(vo.getPassword());
            druidDataSource1.setUsername(vo.getUsername());
            druidDataSource1.setDriverClassName(vo.getDriverClassName());
            druidDataSource1.setBreakAfterAcquireFailure(true);
            DruidPooledConnection connection = druidDataSource1.getConnection(3000);
            if (connection != null) {
                druidDataSource.restart();
                druidDataSource.setUrl(vo.getUrl());
                druidDataSource.setPassword(vo.getPassword());
                druidDataSource.setUsername(vo.getUsername());
                druidDataSource.setDriverClassName(vo.getDriverClassName());
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("数据库信息填写有误");
        }
    }
}
